import { getUserInfoStorage, setUserInfoStorage, setUserPositionStorage, getUserPositionStorage, setUserAddressStorage, getUseAddressStorage } from '@/libs/storage'
import { GEO_DEFAULT } from '@/libs/config'
const state = {
  lng: getUserPositionStorage() && getUserPositionStorage().lng ? getUserPositionStorage().lng : GEO_DEFAULT.lng, // 定位经度
  lat: getUserPositionStorage() && getUserPositionStorage().lat ? getUserPositionStorage().lat : GEO_DEFAULT.lat, // 定位纬度
  geoTime: getUserPositionStorage() && getUserPositionStorage().time ? getUserPositionStorage().time : GEO_DEFAULT.time,
  geoAddress: getUseAddressStorage() ? getUseAddressStorage() : GEO_DEFAULT.address,
  userInfo: getUserInfoStorage() // 用户信息
}
const getters = {
  getUserInfo (state) {
    return state.userInfo
  },
  getUserPosition (state) {
    return {
      lng: state.lng,
      lat: state.lat,
      time: state.geoTime,
      address: state.geoAddress
    }
  }
}
const mutations = {
  setUserInfo (state, data) {
    state.userInfo = { ...data }
  },
  setUserPosition (state, { lng, lat, time }) {
    state.lng = lng
    state.lat = lat
    state.geoTime = time
  },
  setGeoAddress (state, data) {
    state.geoAddress = data
  }
}
const actions = {
  // 保存用户信息
  saveUserInfo ({ commit }, data) {
    setUserInfoStorage(data)
    commit('setUserInfo', data)
  },
  saveUserPosition ({ commit }, data) {
    let { lng, lat, time } = data
    commit('setUserPosition', { lng, lat, time })
    if (lng && lat) {
      setUserPositionStorage({ lng, lat, time })
    }
  },
  saveGeoAddress ({ commit }, data) {
    setUserAddressStorage(data)
    commit('setGeoAddress', data)
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
